<?php
/*
 * Update the recipe information
 */
F3::call('authentication.php');
if (F3::exists('auth_error'))
{
  // authentication failed
  return;
}

$rid = F3::get('PARAMS["recipe_id"]');
$uid = F3::get('SESSION.user_id');

$param = array('1'=>$rid);
$result = DB::sql("SELECT * from recipes where rid = ?", $param);
if(count($result)==0){
	//the recipe doesn't exist
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Recipe doesn't exist.");
	echo json_encode($err);
	return;
}

$author= $result[0]['author'];

if($author != $uid){
	//only the author can change the recipe
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Only the author can change the recipe, not authorized.");
	echo json_encode($err);
	return;
}

parse_str(file_get_contents("php://input"), $put_vars);

if(isset($put_vars['directions'])){
	$directions = $put_vars['directions'];
	$direction = explode("|",$directions);
	$param = array('1'=>$rid);
	DB::sql("DELETE from directions where rid = ?",$param);
	for($i=0; $i<count($direction); $i++){
		$param = array('1'=>$rid, '2'=>($i+1), '3'=>$direction[$i]);
		DB::sql("INSERT INTO directions(rid, step, details) VALUES (?,?,?)",$param);
	}
}

if(isset($put_vars['tag'])){
	$tags = $put_vars['tag'];
	$tag = explode(":", $tags);
	$param = array('1'=>$rid);
	DB::sql("DELETE from recipe_tags where rid = ?",$param);
	foreach($tag as $a){
		$param = array('1'=>$a);
		$tag_id = DB::sql("SELECT id from tags where name = ?", $param);
		if(count($tag_id)==0){//there doesn't exist this tag yet, we need to add the id and tag
			DB::sql("INSERT INTO tags(name) VALUES (?)", $param);
			$db = F3::get('DB');
			$pdo = $db->pdo;
			$tag_id = $pdo->lastInsertId();
			$param = array('1'=>$rid,'2'=>$tag_id);
			DB::sql("INSERT INTO recipe_tags(rid, tid) VALUES (?,?)",$param);
		}
		else{//there exists the tag
			$param = array('1'=>$rid, '2'=>$tag_id[0]['id']);
			DB::sql("INSERT INTO recipe_tags(rid, tid) VALUES (?,?)",$param);
		}
	}
}

$fields = array('link','photo','prep_time','inactive_time','cook_time','privacy','yield');

foreach ($fields as $field)
{
	if (isset($put_vars[$field]))
	{
		// optional field exists, update the recipe
		$param = array('1' => $put_vars[$field], '2' => $rid);
		DB::sql("UPDATE recipes SET $field = ? WHERE rid = ?", $param);
	}
}

header('HTTP/1.1 204');
header("Content-Type: application/json");
$response = array('1'=>"success");
echo json_encode($response);
return;

?>